<?php

namespace app\common\service;

use app\common\model\banxi\organization\Organization;
use app\common\model\banxi\organization\OrganizationUser;
use app\common\model\banxi\organization\OrganizationUserPoster;

class PosterService extends ApiService
{

    /**
     * 生成海报
     * @param $organizationId int 机构id
     * @param $organizationUserId int 教练id
     * @return false|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createPoster(int $organizationId, int $organizationUserId): mixed
    {
        //机构信息
        $organizationInfo = Organization::where('id', $organizationId)->find();
        if (!$organizationInfo) {
            $this->setError('机构不存在');
            return false;
        }
        //教练信息
        $organizationUserInfo = OrganizationUser::where('id', $organizationUserId)->find();
        if (!$organizationUserInfo) {
            $this->setError('教练不存在');
            return false;
        }
        //记录的海报信息
        $userPosterInfo = OrganizationUserPoster::where('organizationUserId', $organizationUserId)->find();
        //获取海报背景图
        $configService = new ConfigService();
        $organizationPoster = $configService->getSysConfigValue('organization_poster');
        if (!$organizationPoster) {
            $this->setError($configService->getError());
            return false;
        }
        //存在且没有换机构和换背景图
        if ($userPosterInfo && ($userPosterInfo['organizationId'] == $organizationId && $userPosterInfo['posterImage'] == $organizationPoster)) {
            return $userPosterInfo['userPosterBase'];
        }
        //不存在或换了机构
        // $wechatPosterBase = $userPosterInfo['wechatPosterBase'] ?? '';
        // if (!$wechatPosterBase || $userPosterInfo['organizationId'] != $organizationId) {
        //     $service = new WeAppletService();
        //     $wechatPosterBase = $service->createQRCode($organizationId);
        //     if (!$wechatPosterBase) {
        //         $this->setError($service->getError());
        //         return false;
        //     }
        // }
        $wechatPosterBase = $configService->getSysConfigValue('wx_qrcode');
        if (!$wechatPosterBase) {
            $this->setError('获取app下载码失败');
            return false;
        }
        //合成海报
        $userPosterBase = $this->postcardShareImage($organizationPoster, $wechatPosterBase, 350);
        if (!$userPosterBase) {
            return false;
        }
        //更新或创建数据
        if ($userPosterInfo) {
            $userPosterInfo->organizationId = $organizationId;
            $userPosterInfo->posterImage = $organizationPoster;
            $userPosterInfo->wechatPosterBase = $wechatPosterBase;
            $userPosterInfo->userPosterBase = $userPosterBase;
            $userPosterInfo->updateBy = $organizationUserInfo['account'];
            $userPosterInfo->save();
        } else {
            OrganizationUserPoster::create([
                'organizationId' => $organizationId,
                'organizationUserId' => $organizationUserId,
                'posterImage' => $organizationPoster,
                'wechatPosterBase' => $wechatPosterBase,
                'userPosterBase' => $userPosterBase,
                'createBy' => $organizationUserInfo['account'],
                'updateBy' => $organizationUserInfo['account'],
            ]);
        }
        return $userPosterBase;
    }

    public function streamToBase64($imageUrl)
    {
        // 初始化 cURL 会话以获取 COS 图片
        $UploadService = new UploadService();
        $imageData = $UploadService->downloadBody($imageUrl);
        if (!$imageData) {
            $this->setError($UploadService->getError());
            return false;
        }
        // 打开背景图片
        $backgroundImage = imagecreatefromstring($imageData);
        if (!$backgroundImage) {
            return false;
        }
        return $backgroundImage;
    }

    /**
     * 合成海报
     * @param $cosImageUrl string cos图片url
     * @param $base64Image string 微信小程序二维码base64图片
     * @param $overlayWidth int 叠加图片宽度
     * @return false|string
     */
    public function postcardShareImage(string $cosImageUrl, string $qrcodeImage, int $overlayWidth): false|string
    {
        $backgroundImage = $this->streamToBase64($cosImageUrl);
        if (!$backgroundImage) {
            return false;
        }
        if (filter_var($qrcodeImage, FILTER_VALIDATE_URL) !== false) {
            $overlayImage = $this->streamToBase64($qrcodeImage);
            if (!$overlayImage) {
                return false;
            }
        } else {
            // 解码 Base64 数据
            $overlayData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $qrcodeImage), true);
            if (!$overlayData) {
                imagedestroy($backgroundImage);
                return false;
            }
            // 打开叠加图片
            $overlayImage = imagecreatefromstring($overlayData);
            if (!$overlayImage) {
                imagedestroy($backgroundImage);
                return false;
            }
        }
        // 获取背景图片和叠加图片的宽度和高度
        $backgroundWidth = imagesx($backgroundImage);
        $backgroundHeight = imagesy($backgroundImage);
        $overlayOriginalWidth = imagesx($overlayImage);
        $overlayOriginalHeight = imagesy($overlayImage);

        // 计算叠加图片缩放后的高度
        $overlayHeight = ($overlayWidth / $overlayOriginalWidth) * $overlayOriginalHeight;

        // 创建一个临时图像来存储缩放后的叠加图片
        $resizedOverlay = imagecreatetruecolor($overlayWidth, $overlayHeight);
        imagecopyresampled($resizedOverlay, $overlayImage, 0, 0, 0, 0, $overlayWidth, $overlayHeight, $overlayOriginalWidth, $overlayOriginalHeight);

        // 计算叠加图片的位置（这里放在右下角）
        $overlayX = $backgroundWidth - $overlayWidth - 130; // 右边距 130 像素
        $overlayY = $backgroundHeight - $overlayHeight - 60; // 下边距 60 像素

        // 将缩放后的叠加图片合并到背景图片上
        imagecopy($backgroundImage, $resizedOverlay, $overlayX, $overlayY, 0, 0, $overlayWidth, $overlayHeight);

        // 销毁临时图像
        imagedestroy($overlayImage);
        imagedestroy($resizedOverlay);

        // 将合并后的图片转换为 Base64 编码
        ob_start();
        imagepng($backgroundImage);
        $imageContent = ob_get_clean();
        imagedestroy($backgroundImage);
        return 'data:image/png;base64,' . base64_encode($imageContent);
    }
}